<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * addadj.php
 * Began: Sat January 4 2003
 * 
 * $Id: addadj.php 541 2008-05-20 06:56:16Z rspeicher $
 * 
 ******************************/
 
define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

$fv = new Form_Validate;

// Obtain var settings
$adjustment_id = ( !empty($_REQUEST[URI_ADJUSTMENT]) ) ? intval($_REQUEST[URI_ADJUSTMENT]) : '';
$confirm = ( !empty($_POST['confirm']) ) ? true : false;

// Start session management
$user->start();
$user->setup();

// Delete confirmation
// If they didn't confirm, redirect them to the last page they were on
if ( isset($_POST['cancel']) )
{
    if ( $adjustment_id )
    {
        $redirect = 'addadj.php'.$SID.'&' . URI_ADJUSTMENT . '='.$adjustment_id;
    }
    else
    {
        $redirect = 'addadj.php'.$SID;
    }

    redirect($redirect);
}

// Figure out what submit button was pressed
$add    = ( isset($_POST['add']) ) ? true : false;
$update = ( isset($_POST['update']) ) ? true : false;
$delete = ( isset($_POST['delete']) ) ? true : false;

// Figure out action based on submit
if ( $add )
{
    $user->check_auth('a_groupadj_add');
    $action = 'add';
}
elseif ( $update )
{
    $user->check_auth('a_groupadj_upd');
    $action = 'update';
}
elseif ( ($delete) || ($confirm) )
{
    $user->check_auth('a_groupadj_del');
    $action = 'delete';
}
else
{
    $user->check_auth('a_groupadj_');
    $action = 'display';
}

//
// Error Checking and variable initialization
//
if ( ($add) || ($update) || ($delete) )
{
    $_POST = htmlspecialchars_array($_POST);
    
    $adjustment_added_by = $user->data['username'];
    $adjustment_updated_by = $user->data['username'];
    
    $fv->is_number('adjustment_value', $user->lang['fv_number_adjustment']);
    $fv->is_filled('adjustment_value', $user->lang['fv_required_adjustment']);
    
    if ( $fv->is_error() )
    {
        $action = 'display';
    }
}

//
// Get relevant data
//
if ( $adjustment_id )
{
    $sql = 'SELECT adjustment_value, member_name
            FROM ' . ADJUSTMENTS_TABLE . "
            WHERE adjustment_id='".$adjustment_id."'";
    $result = $db->query($sql);
    if ( !$row = $db->fetch_record($result) )
    {
        message_die($user->lang['error_invalid_adjustment_provided']);
    }
    $db->free_result($result);

    // If member name is set, it's an individual adjustment - put them back on that script
    if ( isset($row['member_name']) )
    {
        redirect('addiadj.php' . $SID . '&' . URI_ADJUSTMENT . '='.$adjustment_id);
    }
    
    $adjustment = array(
        'adjustment_value' => post_or_db('adjustment_value', true, $row)
    );
}
else
{
    $adjustment = array(
        'adjustment_value' => post_or_db('adjustment_value', false)
    );
}

//
// Processing
//
switch ( $action )
{
    //
    // Add
    //
    case 'add':
        $adjustment_date = time();
        
        $sql = 'SELECT member_id, member_name
                FROM ' . MEMBERS_TABLE;
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $sql = 'UPDATE ' . MEMBERS_TABLE . '
                    SET member_adjustment = member_adjustment+'.remove_quote_escape($_POST['adjustment_value'])."
                    WHERE member_id='".$row['member_id']."'";
            $db->query($sql);
        }
        $db->free_result($result);
        
        $sql = 'INSERT INTO ' . ADJUSTMENTS_TABLE . "
                (adjustment_id, adjustment_value, adjustment_date, adjustment_added_by)
                VALUES ('NULL','".remove_quote_escape($_POST['adjustment_value'])."','".$adjustment_date."','".$adjustment_added_by."')";
        $db->query($sql);
        $this_adjustment_id = $db->insert_id();
        
        $log_action = array(
            'header' => '{L_ACTION_GROUPADJ_ADDED}',
            'id' => $this_adjustment_id,
            '{L_ADJUSTMENT}' => $_POST['adjustment_value'],
            '{L_ADDED_BY}' => $adjustment_added_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );
        
        $success_message = sprintf($user->lang['admin_add_adj_success'], $eqdkp->config['dkp_name'], $_POST['adjustment_value']);
        
        $link_list = generate_admin_success_links(array(
            $user->lang['list_groupadj'] => 'listadj.php'.$SID,
            $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
        );
        
        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
        
        break;
    //
    // Update
    //
    case 'update':
        // Get the old data
        $sql = 'SELECT adjustment_value, adjustment_date
                FROM ' . ADJUSTMENTS_TABLE . "
                WHERE adjustment_id='".$adjustment_id."'";
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $old_adjustment = array(
                'adjustment_value' => addslashes($row['adjustment_value']),
                'adjustment_date' => addslashes($row['adjustment_date'])
            );
        }
        $db->free_result($result);
        
        $sql = 'SELECT member_id, member_name, member_firstraid
                FROM ' . MEMBERS_TABLE;
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            // If their first raid was before/on the adjustment date, then they
            // would have received this adjustment - remove it from their adjustment column
            if ( $row['member_firstraid'] <= $old_adjustment['adjustment_date'] )
            {
                $sql = 'UPDATE ' . MEMBERS_TABLE . "
                        SET member_adjustment = member_adjustment-".$old_adjustment['adjustment_value']."
                        WHERE member_id='".$row['member_id']."'";
                $db->query($sql);
            }
            // Add the new adjustment regardless
            $sql = 'UPDATE ' . MEMBERS_TABLE . "
                    SET member_adjustment = member_adjustment+".remove_quote_escape($_POST['adjustment_value'])."
                    WHERE member_id='".$row['member_id']."'";
            $db->query($sql);
        }
        $db->free_result($result);
        
        $sql = 'UPDATE ' . ADJUSTMENTS_TABLE . "
                SET adjustment_value='".$_POST['adjustment_value']."', adjustment_updated_by='".$adjustment_updated_by."'
                WHERE adjustment_id='".$adjustment_id."'";
        $db->query($sql);
        
        $log_action = array(
            'header' => '{L_ACTION_GROUPADJ_UPDATED}',
            'id' => $adjustment_id,
            '{L_ADJUSTMENT_BEFORE}' => $old_adjustment['adjustment_value'],
            '{L_ADJUSTMENT_AFTER}' => find_difference($old_adjustment['adjustment_value'], $_POST['adjustment_value']),
            '{L_UPDATED_BY}' => $adjustment_added_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );
        
        $success_message = sprintf($user->lang['admin_update_adj_success'], $eqdkp->config['dkp_name'], $_POST['adjustment_value']);
        
        $link_list = generate_admin_success_links(array(
            $user->lang['list_groupadj'] => 'listadj.php'.$SID,
            $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
        );
        
        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
        
        break;
    //
    // Delete
    //
    case 'delete':
        if ( !$confirm )
        {
            confirm_delete($user->lang['confirm_delete_adj'], URI_ADJUSTMENT, $adjustment_id, 'addadj.php'.$SID);
        }
        else
        {
            // Get the old data
            $sql = 'SELECT adjustment_value, adjustment_date
                    FROM ' . ADJUSTMENTS_TABLE . "
                    WHERE adjustment_id='".$adjustment_id."'";
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                $old_adjustment = array(
                    'adjustment_value' => addslashes($row['adjustment_value']),
                    'adjustment_date' => addslashes($row['adjustment_date'])
                );
            }
            $db->free_result($result);
            
            $sql = 'SELECT member_id, member_name, member_firstraid
                    FROM ' . MEMBERS_TABLE;
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                // If their first raid was before/on the adjustment date, then they
                // would have received this adjustment - remove it from their adjustment column
                if ( $row['member_firstraid'] <= $old_adjustment['adjustment_date'] )
                {
                    $sql = 'UPDATE ' . MEMBERS_TABLE . "
                            SET member_adjustment = member_adjustment-".$old_adjustment['adjustment_value']."
                            WHERE member_id='".$row['member_id']."'";
                    $db->query($sql);
                }
            }
            $db->free_result($result);
            
            $sql = 'DELETE FROM ' . ADJUSTMENTS_TABLE . "
                    WHERE adjustment_id='".$adjustment_id."'";
            $db->query($sql);
            
            $log_action = array(
                'header' => '{L_ACTION_GROUPADJ_DELETED}',
                'id' => $adjustment_id,
                '{L_ADJUSTMENT}' => $old_adjustment['adjustment_value']);
            $eqdkp->log_insert(array(
                'log_type' => $log_action['header'],
                'log_action' => $eqdkp->make_log_action($log_action),
                'log_ipaddress' => $user->ip,
                'log_sid' => $user->session_id,
                'log_result' => '{L_SUCCESS}',
                'admin_id' => $user->data['user_id'])
            );
            
            $success_message = sprintf($user->lang['admin_delete_adj_success'], $eqdkp->config['dkp_name'], $old_adjustment['adjustment_value']);
            
            $link_list = generate_admin_success_links(array(
                $user->lang['list_groupadj'] => 'listadj.php'.$SID,
                $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
            );
            
            message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
            
        } // confirmed
        break;
    //
    // Display form
    //
    case 'display':
        $tpl->assign_vars(array(
            'F_ADD_ADJUSTMENT' => 'addadj.php'.$SID,
            'ADJUSTMENT_ID' => $adjustment_id,
            
            'ADJUSTMENT' => $adjustment['adjustment_value'],
            
            'L_ADD_ADJ_TITLE' => $user->lang['addadj_title'],
            'L_ADJUSTMENT_VALUE' => $user->lang['adjustment_value'],
            'L_ADJUSTMENT_VALUE_NOTE' => '(' . strtolower($user->lang['adjustment_value_note']) . ')',
            'L_ADD_ADJUSTMENT' => $user->lang['add_adjustment'],
            'L_RESET' => $user->lang['reset'],
            'L_UPDATE_ADJUSTMENT' => $user->lang['update_adjustment'],
            'L_DELETE_ADJUSTMENT' => $user->lang['delete_adjustment'],

            'FV_ADJUSTMENT' => $fv->generate_error('adjustment_value'),

            'MSG_VALUE_EMPTY' => $user->lang['fv_required_adjustment'],
            
            'S_ADD' => ( !$adjustment_id ) ? true : false)
        );
        
        $page_title = sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['addadj_title'];
        include_once($eqdkp_root_path . 'includes/page_header.php');
        
        $tpl->set_filenames(array(
            'body' => 'admin/addadj.html')
        );
        
        include_once($eqdkp_root_path . 'includes/page_tail.php');
        break;
} // Processing
?>